<template>
  <div>
    <div style="clear:both">
      <el-button style="float:left;margin-right:10px" size="small" @click="downloadTable">下载导入表</el-button>
      <el-upload
        :auto-upload="false"
        :on-change="handleFile"
        :before-remove="beforeRemove"
        :on-exceed="handleExceed"
        :limit="1"
        action
      >
        <el-button size="small" type="primary">选择核对表</el-button>
        <div slot="tip" class="el-upload__tip">只能上传核查表,不能解析其他表格</div>
      </el-upload>
      <el-checkbox v-model="checked">排序汇总</el-checkbox>
    </div>
    <el-table
      v-show="table_fields.length > 0"
      :data="show_table_data"
      style="width: 100%"
      max-height="400px"
      v-loading="loading"
    >
      <el-table-column
        :key="index"
        v-for="(val, index) in table_fields"
        :prop="val"
        :label="val"
        width="150"
      ></el-table-column>
      <el-table-column fixed="right" label="操作" width="60">
        <template slot-scope>
          <el-button type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>{{tip_message}}</div>
  </div>
</template>
<script>
import XLSX from "xlsx";

export default {
  data() {
    return {
      checked: false,
      loading: false,
      all_fields: [
        "资产编码",
        "设备名称",
        "设备型号",
        "出厂编号",
        "注册证号",
        "使用科室",
        "存放地点",
        "生产厂商",
        "品牌",
        "68码",
        "是否计量",
        "风险等级",
        "折旧年限(年)",
        "供应商",
        "财务编码",
        "合同编码",
        "规格",
        "单位",
        "资产状态",
        "使用状态",
        "科室编号",
        "设备原值",
        "设备残值",
        "设备净值",
        "启用日期",
        "出厂日期",
        "产地",
        "保修期限(月)",
        "供应商联系人",
        "供应商电话",
        "售后工程师",
        "售后电话",
        "新折旧年限",
        "核算折旧年限",
        "核算折旧开始时间",
        "安装日期",
        "验收日期",
        "入库日期",
        "出库日期",
        "财务分类",
        "辅助分类",
        "68分类",
        "设备用途",
        "设备来源",
        "发票号",
        "采购人",
        "负责人",
        "经费来源",
        "财政拨款",
        "自筹金额",
        "送修情况",
        "成本核算",
        "是否进口",
        "账外",
        "低值",
        "计量编码",
        "备注",
        "院区"
      ],
      file_name: null,
      table_fields: [],
      table_data: [],
      tip_message: null
    };
  },
  computed: {
    name: function() {
      let name_list = this.file_name.split(".");
      name_list[0] = name_list[0] + "导入表";
      let name = name_list[0] + ".xls";
      return name;
    },
    show_table_data: function() {
      let tables = this.table_data.map(vals => {
        let arr = new Object();
        vals.forEach((val, index) => {
          arr[this.table_fields[index]] = val;
        });
        return arr;
      });
      return tables;
    },
    out_fields: function() {
      let out_fields = this.table_fields.map(val => {
        switch (val) {
          case "出厂编码":
            val = "出厂编号";
            break;
          case "生产厂家":
            val = "生产厂商";
            break;
        }
        return val;
      });
      return out_fields;
    },
    full_table: function() {
      let datas = [this.out_fields.concat(this.all_fields)].concat(
        this.table_data
      );
      return datas;
    }
  },
  watch: {
    checked() {
      if (this.checked) {
        this.sortTableData(this.table_data);
      } else {
        this.table_data.reverse();
      }
      let names = this.table_data.map(item => {
        return item[1];
      });
      let message = "";
      let number = 1;
      names.forEach((item, index, self) => {
        if (self.indexOf(item) == index) {
          if (index != 0) {
            message += `${self[index - 1]} ${number}台、`;
          }
          number = 1;
        } else {
          number++;
        }
      });
      this.tip_message = message;
    }
  },
  methods: {
    handleFile(e) {
      this.loading = true;
      this.file_name = e.name;
      let f = e.raw;
      let reader = new FileReader();
      reader.onload = e => {
        let data = new Uint8Array(e.target.result);
        let workbook = XLSX.read(data, { type: "array" });
        let name =
          workbook.SheetNames.length > 1 ? "核对表" : workbook.SheetNames[0];
        let worksheet = workbook.Sheets[name];
        this.deleteEndRow(worksheet, 1);
        let table_json = XLSX.utils.sheet_to_json(worksheet, {
          range: 1,
          header: 1
        });
        this.table_fields = table_json.shift();
        this.table_data = table_json.filter(item => {
          return item[0] != null;
        });
        let remove_id = this.table_fields.indexOf("备注");
        this.table_fields.splice(remove_id, 1);
        this.table_data.forEach(item => {
          item.splice(remove_id, 1);
        });
        this.all_fields = this.all_fields.filter(item => {
          return !this.out_fields.some(val => {
            return item == val;
          });
        });
        this.loading = false;
      };
      reader.readAsArrayBuffer(f);
    },
    sortTableData(datas) {
      datas
        .sort(function(a, b) {
          let x = a[1].toLowerCase();
          let y = b[1].toLowerCase();
          if (x < y) {
            return -1;
          }
          if (x > y) {
            return 1;
          }
          return 0;
        })
        .reverse();
    },
    encodeCell(r, c) {
      return XLSX.utils.encode_cell({ r, c });
    },
    deleteEndRow(worksheet, r) {
      const range = XLSX.utils.decode_range(worksheet["!ref"]);
      for (let row = range.e.r - r; row <= range.e.r; row++) {
        for (let col = 0; col <= range.e.c; col++) {
          delete worksheet[this.encodeCell(row, col)];
        }
      }
    },
    downloadTable() {
      if (this.file_name) {
        let worksheet = XLSX.utils.aoa_to_sheet(this.full_table);
        var new_workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(new_workbook, worksheet, "Worksheet");
        XLSX.writeFile(new_workbook, this.name);
      } else {
        this.$message.warning("请在选择核对表后下载导入表");
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，不可选择 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    }
  }
};
</script>
<style></style>
